package com.njxzc.igo.utils;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.connection.C3P0ConnectionProvider;
public class HibernateUtils {
	private static SessionFactory factory = null;

	static {
		try {
			Configuration cfg = new Configuration().configure();
			factory = cfg.buildSessionFactory();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static SessionFactory getSessionFactory() {
		return factory;
	}
	  
	    public static final ThreadLocal<Session> session  
	        = new ThreadLocal<Session>();  
	    //创建Session  
	    public static Session getSession()  
	        throws HibernateException  
	    {  
	        //通过线程对象.get()方法安全创建Session  
	        Session s = session.get();  
	        if (s == null)  
	        {  
	            s = factory.openSession();  
	            session.set(s);  
	        }  
	        return s;  
	    }  
	    //关闭Session  
	    public static void closeSession()  
	        throws HibernateException  
	    {  
	        Session s = session.get();  
	        if (s != null)  {
	        	s.close();
	        }
	        session.set(null);  
	    }  
	}  


